using CommandLine;
using Furion;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using SpeedOctopusNet.CommunicationServer.Transmission;

namespace SpeedOctopusNet.CommunicationServer;

public class Program
{
    /// <summary>
    /// 工作目录，用于指向数据存储根目录
    /// </summary>
    public static string WorkDir { get; private set; }

    /// <summary>
    /// 实例编号
    /// </summary>
    public static string InstanceCode { get; private set; }

    /// <summary>
    /// 启动时间
    /// </summary>
    public static DateTime StartTstamp { get; private set; }

    /// <summary>
    /// 本进程Id
    /// </summary>
    public static int ProcessId { get; private set; }

    private static ILogger<Program> s_Logger;

    public static async Task Main(string[] args)
    {
        await Parser.Default.ParseArguments<StartupParams>(args).WithParsedAsync(Run);
    }

    public static async Task Run(StartupParams param)
    {
        try
        {
            var host = CreateHostBuilder(param);
        }
        catch (Exception ex)
        {
            throw;
        }
    }

    private static IHost CreateHostBuilder(StartupParams param)
    {
        var options = GenericRunOptions.Default.ConfigureBuilder(builder => builder.ConfigureServices(ConfigureServices));
        var host = Serve.Run(options);

        return host;
    }

    private static async void ConfigureServices(HostBuilderContext context, IServiceCollection services)
    {
        services.AddFileLogging(Path.Combine(AppContext.BaseDirectory, "logs", $"{InstanceCode}-{{0:yyyy}}-{{0:MM}}-{{0:dd}}.log"), options =>
        {
            options.FileNameRule = fileName => string.Format(fileName, DateTime.Now);
        });

        s_Logger = App.GetService<ILogger<Program>>();

        services.AddHostedService<TransmissionService>();
    }
}
